package com.chapter.sample.answer.multiplex;

import lombok.Data;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalDemo {
    public static void main(String[] args) throws InterruptedException {

        MyData myData = new MyData();
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            //10个顾客请求线程,池子里有3个受理线程，负责处理业务
            for (int i = 1; i <= 10; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    try {
                        Integer beforeInt = myData.threadLocalField.get();
                        myData.add();
                        Integer afterInt = myData.threadLocalField.get();
                        System.out.println(Thread.currentThread().getName() + "工作窗口，受理第" + finalI + "个顾客业务 beforeInt:" + beforeInt + " afterInt:" + afterInt);
                    } finally {
                        //线程池，复用同一个线程，线程中的本地遍历也复用
                        myData.threadLocalField.remove();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

    private static void threadLocalTotal() throws InterruptedException {
        SU7 su7 = new SU7();

        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(3) + 1; j++) {
                        su7.saleTotal();
                        su7.salePersonal();
                    }
                    System.out.println(Thread.currentThread().getName() + "号销售卖出：" + su7.salePersonal.get());
                } finally {
                    countDownLatch.countDown();
                }
            }, "su7").start();
        }
        countDownLatch.await();
        System.out.println("销售总额：" + su7.getSaleTotal());
    }
}

@Data
class SU7 {
    private int saleTotal;

    public synchronized void saleTotal() {
        saleTotal++;
    }

    /*ThreadLocal<Integer> salePersonal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/
    ThreadLocal<Integer> salePersonal = ThreadLocal.withInitial(() -> {
        return 0;
    });

    public void salePersonal() {
        salePersonal.set(1 + salePersonal.get());
    }
}

class MyData {
    ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(() -> 0);

    public void add() {
        threadLocalField.set(threadLocalField.get() + 1);
    }
}
